<template>
  <div>
    <a-card style="width: 100% ;height:100%">
      <div slot="title">
        <a-icon
          style="color:rgb(24, 144, 255); font-size:20px"
          type="arrow-left"
          @click="()=>{$router.back()}"
        />&nbsp;&nbsp;
        <span>返回</span>
      </div>
      <a-form :form="form" class="login-form" @submit="handleSubmit">
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }" label="商品名称">
          <a-input
            v-decorator="[
          'name',
          { rules: [{ required: true, message: '必须输入商品名称！' }] },
        ]"
            placeholder="请输入商品名称"
          />
        </a-form-item>
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }" label="商品描述">
          <a-textarea
            v-decorator="[
          'desc',
          { rules: [{ required: true, message: '必须输入商品描述！' }] },
        ]"
            placeholder="请输入商品描述"
            :rows="4"
          />
        </a-form-item>
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }" label="商品价格">
          <a-input
            v-decorator="[
          'price',
          { rules: [{ required: true, message: '必须输入商品价格！' }] },
        ]"
            placeholder="请输入商品价格"
            addonAfter="元"
            type="number"
          />
        </a-form-item>
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }" label="商品分类">
          <a-cascader
            v-decorator="[
          'category' ,
          { rules: [{ required: true, message: '必须选择商品分类！' }] },
        ]"
            :options="options"
            @change="categoryChange"
            changeOnSelect
          />
        </a-form-item>
        <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 8 }" label="商品图片">
          <a-upload
            action="/admin/manage/img/upload"
            accept="image/*"
            name="image"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 3">
              <a-icon type="plus" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item :label-col="{ span:4}" :wrapper-col="{ span: 16 }" label="商品商品详情">
          <editor v-model="productDetail" @bindQuill="bindQuill" />
        </a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import Editor from "../../../components/Editor/Editor";
import {
  reqCategorys,
  reqAddOrUpdateProduct,
  reqDeleteImg
} from "../../../api/index";
import { format } from "path";
import { message } from "ant-design-vue";
export default {
  data() {
    return {
      _id:undefined,//用于判断是修改还是添加  _id:undefined 为添加  _id 有值则为修改并作为参数
      productDetail: {}, //商品详情
      previewVisible: false,
      previewImage: "",
      category: "",
      fileList: [],
      options: []
    };
  },
  async created() {
    //获取一级分类
    var result = await reqCategorys(0);
    var data = result.data;
    this.options.splice(0, this.options.length);
    data.forEach((item, index) => {
      var option = {
        value: item._id,
        label: item.name,
        parentId: item.parentId
      };
      this.options.push(option);
    });
  },
  async mounted() {
    if (this.$route.params.product !== undefined) {
      var product = this.$route.params.product.value;
      console.log(product);
      var {
        categoryId,
        pCategoryId,
        name,
        desc,
        price,
        detail,
        imgs,
        _id
      } = product;
      this._id = _id
      //  category, name, price, desc
      this.categoryChange(pCategoryId);
      var category = [pCategoryId, categoryId];
      this.form.setFieldsValue({ category: category });
      this.form.setFieldsValue({ name });
      this.form.setFieldsValue({ desc });
      this.form.setFieldsValue({ price });
      // this.productDetail = detail
      this.quill.setContents([{ insert: detail }]);
      var BASE_IMG_URL = 'http://localhost:5000/upload/'
      if (imgs && imgs.length > 0) {
        this.fileList = imgs.map((img, index) => ({
          uid: -index, // 每个file都有自己唯一的id
          name: img, // 图片文件名
          status: "done", // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
          url: BASE_IMG_URL + img
        }));
      }
      // this.quill.setContents([{ insert: 'detail' },])
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
  },
  methods: {
    bindQuill(quill) {
      //监听子组件editor发射的事件 (子组件editor将quill对象发射给父组件绑定)

      this.quill = quill;
    },
    //商品分类选择框改变
    async categoryChange(value) {
      this.category = value;
      var result = await reqCategorys(value);
      var data = result.data;
      var subOption = [];
      data.forEach((item, index) => {
        var option = {
          value: item._id,
          label: item.name,
          parentId: item.parentId
        };
        subOption.push(option);
      });
      var newOpations = this.options.map(item => {
        if (item.value == value) {
          item.children = subOption;
          return item;
        }
        return item;
      });
      this.options.splice(0, this.options.length);
      this.options.push(...newOpations);
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields(async (err, values) => {
        if (!err) {
          var { category, name, price, desc } = values;
          var categoryId = category[category.length - 1];
          var pCategoryId =
            category.length == 1 ? 0 : category[category.length - 2];
          var detail = "";
          this.productDetail.ops.forEach((e, index) => {
            detail += e.insert;
          });
          var imgs = [];
          this.fileList.forEach(file => {
            imgs.push(file.name);
          });
          var _id = this._id
          var product = {
            _id,
            name,
            desc,
            price,
            imgs,
            detail,
            pCategoryId,
            categoryId
          };
          const result = await reqAddOrUpdateProduct(product);
          if (result.status == 0) {
            this.$router.push("/product");
            message.success(this._id?"修改成功!":"添加成功!");
          } else {
            message.error(this._id?"修改失败!":"添加失败!");
          }
          console.log(result);
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    async handleChange({ file, fileList }) {
      console.log(
        "handleChange()",
        file.status,
        fileList.length,
        file === fileList[fileList.length - 1]
      );

      // 一旦上传成功, 将当前上传的file的信息修正(name, url)
      if (file.status === "done") {
        const result = file.response; // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
        if (result.status === 0) {
          message.success("上传图片成功!");
          const { name, url } = result.data;
          file = fileList[fileList.length - 1];
          file.name = name;
          file.url = url;
          console.log(fileList);
        } else {
          message.error("上传图片失败");
        }
      } else if (file.status === "removed") {
        // 删除图片
        const result = await reqDeleteImg(file.name);
        if (result.status === 0) {
          message.success("删除图片成功!");
        } else {
          message.error("删除图片失败!");
        }
      }

      // 在操作(上传/删除)过程中更新fileList状态
      this.fileList = fileList;
    }
  },
  components: {
    editor: Editor
  }
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>